import sys

try:
    from ujson import loads
except:
    from json import loads


q = {}
req = []

DBG=0
WARNED = 0

IOCTL = []

error = False

def finalize():
    global q,req
    okdel = []
    for key in q:
        if not key in req:
            okdel.append( key )

    while len(okdel):
        key = okdel.pop()
        q.pop(key)

def step(*jsdata):
    global q,IOCTL, error
    if not aio.io.error and len(jsdata):
        try:
            jsdata =  loads(jsdata[0])
            #if DBG and jsdata: print("\n << IO=",jsdata)
            q.update( jsdata )
            ioctl = q.get('ioctl',())
            if len(ioctl):
                print("IOCTL",ioctl)
                IOCTL.extend( ioctl )
        except Exception as e :
            sys.print_exception(e, sys.stderr)
            aio.lib.io_error = True

        # try to prevent leaks
        if len(q)>40:
            finalize()
        # or fail
        if not WARNED and len(q) > 80:
            print("aio.lib.io.q is getting huge, do you need some discard ?")
            aio.io.error = True
    return None


async def ctl(ctx, ev, tmout=-1):
    global IOCTL
    ioctl = "{}:{}".format((ctx.sid), (ev))
    while tmout:
        if ioctl in IOCTL:
            print(ioctl,"GOT")
            return True
        if tmout>0:
            tmout -= 1
        await aio.asleep_ms(1)
    raise Exception('IOCTL.timeout')


def network():
    from aio.network import StreamReader, StreamWriter, start_server
    aio.StreamReader = StreamReader
    aio.StreamWriter = StreamWriter
    aio.start_server = start_server

